package com.david.webtest.blog

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.view.View
import android.webkit.*
import android.widget.TextView
import com.david.webtest.R
import com.david.webtest.utils.HttpUtils
import com.david.webtest.utils.PreferenceUtils
import java.io.File

class BlogWebActivity : Activity() {

    companion object {
        const val INTENT_WEB_URL: String = "INTENT_WEB_URL"
    }

    private var url: String = ""
    private lateinit var mWebView: WebView

    private lateinit var title: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_blog_web)
        mWebView = findViewById(R.id.blog_web_view)
        title = findViewById(R.id.title)
        val webSettings = mWebView.settings


        webSettings.textZoom = 100
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        webSettings.javaScriptEnabled = true
        webSettings.domStorageEnabled = true//支持DOM API
        webSettings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW//解决app中部分页面非https导致的问题
//        webSettings.blockNetworkImage = true
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH)//设置渲染的优先级
//        webSettings.setAppCacheEnabled(true)
        val cachePath = Environment.getExternalStorageDirectory().path + "/blogCache"
        if (!File(cachePath).exists()) {
            File(cachePath).mkdir()
        }
//        webSettings.setAppCachePath(cachePath)
        // 1. 设置缓存路径

//        webSettings.setAppCacheMaxSize(80*1024*1024)
        // 2. 设置缓存大小

//        webSettings.setAppCacheEnabled(true)
        // 3. 开启Application Cache存储机制

        WebView.setWebContentsDebuggingEnabled(true)
        mWebView.webViewClient = object : WebViewClient() {
            override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
                handler.proceed()
            }

            override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
                if (request.url == null || request.url.toString().startsWith("youku://") || request.url.toString().startsWith("tbopen://")) {
                    return false//过滤跳转优酷的native
                }

                try {
                    if (request.url.toString().startsWith("baiduboxapp://")) {
                        return true
                    } else if (!request.url.toString().startsWith("http://") && !request.url.toString().startsWith(
                            "https://"
                        )
                    ) {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(request.url.toString()))
                        startActivity(intent)
                        return true
                    }
                } catch (e: Exception) {//防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    return true//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }

                view.loadUrl(request.url.toString())
                return true
            }

            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
//                webSettings.blockNetworkImage = false
                //判断webview是否加载了，图片资源
                if (!webSettings.loadsImagesAutomatically) {
                    //设置wenView加载图片资源
                    webSettings.loadsImagesAutomatically = true
                }

                if (title.tag == null) {
                    val title = view.title
                    if (!TextUtils.isEmpty(title)) {
                        if (title!!.startsWith("http")) {
                            view.postDelayed(
                                { this@BlogWebActivity.title.text = view.title },
                                3000
                            )
                        } else {
                            this@BlogWebActivity.title.text = title
                        }
                    }
                    HttpUtils.downLoadHtml(url, title)

                }
                PreferenceUtils.getInstance().setBlogName(view.title!!, url)
            }
        }


        url = intent.getStringExtra(INTENT_WEB_URL)!!
        if (TextUtils.isEmpty(url)) {//通过scheme打开webview
            val uri = intent.data
            if (uri != null) {
                try {
                    url = uri.getQueryParameter(INTENT_WEB_URL).toString()
                } catch (e: Exception) {
                    e.printStackTrace()
                }

            }

        }
        mWebView.loadUrl(url)

        findViewById<View>(R.id.blog_share).setOnClickListener { share() }

    }

    override fun onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack()
        } else {
            super.onBackPressed()
        }
    }

    private fun share(){
        val textIntent = Intent(Intent.ACTION_SEND)
        textIntent.type = "text/plain"
        textIntent.putExtra(Intent.EXTRA_TEXT, url)
        startActivity(Intent.createChooser(textIntent, title.text))
    }
}